package com.example.sbeducation.config;

import com.example.sbeducation.exception.BusinessException;
import com.example.sbeducation.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

  @Autowired
  private JwtUtil jwtUtil;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    // 打印当前请求的路径，便于调试
    String requestURI = request.getRequestURI();
    log.debug("拦截到请求: {}", requestURI);

    // 放行OPTIONS请求
    if ("OPTIONS".equals(request.getMethod())) {
      return true;
    }

    // 获取请求头中的token
    String token = request.getHeader("Authorization");
    if (!StringUtils.hasText(token)) {
      log.debug("未携带token");
      throw new BusinessException(401, "未登录");
    }

    log.debug("收到token: {}", token);

    // 去掉Bearer前缀
    if (token.startsWith("Bearer ")) {
      token = token.substring(7);
    }

    // 临时解决方案 - 开发环境中为了方便测试
    // 让所有请求都能通过验证，但仍然记录详细日志
    try {
      if (jwtUtil.isExpired(token)) {
        log.debug("token已过期，将为测试目的继续处理请求");
        // 设置一个默认用户和角色用于测试
        request.setAttribute("userId", 1L);
        request.setAttribute("role", "student");
        return true;
      }

      // 获取token中的用户ID和角色
      Long userId = jwtUtil.getUserId(token);
      String role = jwtUtil.getRole(token);

      log.debug("验证成功: userId={}, role={}", userId, role);

      // 将用户信息放入请求属性中，方便后续使用
      request.setAttribute("userId", userId);
      request.setAttribute("role", role);

      return true;
    } catch (Exception e) {
      log.warn("token验证异常，将为测试目的继续处理请求: {}", e.getMessage());
      // 设置一个默认用户和角色用于测试
      request.setAttribute("userId", 1L);
      request.setAttribute("role", "student");
      return true;
    }
  }
}